package net.looker.monitor.analyzer;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.looker.data.News;


/**
 * 新闻正文分析类
 * @author solosky
 *
 */

public class NewsAnalyzer extends Analyzer
{
	

	/**
	 * 新闻对象，用于保存新闻分析结果
	 */
	private News news;
	
	/**
	 * @param source
	 * @param siteConfig
	 */
	public NewsAnalyzer(News news) 
	{
		super(news.getSource() ,news.getCategory().getSiteConfig());
		this.news = news;
	}
	
	/**
	 * 分析新闻
	 */
	public boolean analyze() 
	{
		//新闻标题
		news.setTitle(analyze("view.indexpatterns.title"));
		//新闻作者
		news.setAuthor(analyze("view.indexpatterns.author"));
		//新闻正文
		news.setContent(analyze("view.indexpatterns.content"));
		//新闻发布时间
		String dateStr = analyze("view.indexpatterns.date");
		news.setDate(analyzeDate(dateStr));
		
		return true;
	}

	@Override
	public Object getAnalyzed()
	{
		return news;
	}
	
	/**
	 * 分析新闻内容
	 */
	private String analyze(String name)
	{
		//建立提取标题和新闻ID的正则表达式
		Pattern pt = Pattern.compile(siteConfig.get(name));
		Matcher mc = pt.matcher(source);
		if (mc.find())
			return mc.group(1);
		else
			return null;
	}
	
	/**
	 * 解析日期
	 */
	private Date analyzeDate(String dateStr)
	{
		String format = siteConfig.get("view.dateFormat");
		if(format==null || dateStr==null)
			return new Date();
		
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			date = new Date();
		}
		
		//处理时间补充信息
		String addition = siteConfig.get("view.dateAddition");
		Calendar calc = Calendar.getInstance();
		calc.setTime(date);
		Calendar curCalc = Calendar.getInstance();
		if(addition!=null){
			//补充年
			if(addition.indexOf('y')!=-1)
				calc.set(Calendar.YEAR, curCalc.get(Calendar.YEAR));
			//补充月
			if(addition.indexOf('M')!=-1)
				calc.set(Calendar.MONTH, curCalc.get(Calendar.MONTH));
			//补充日
			if(addition.indexOf('d')!=-1)
				calc.set(Calendar.DAY_OF_MONTH, curCalc.get(Calendar.DAY_OF_MONTH));
			//补充小时
			if(addition.indexOf('h')!=-1)
				calc.set(Calendar.HOUR_OF_DAY, curCalc.get(Calendar.HOUR_OF_DAY));
			//补充分钟
			if(addition.indexOf('m')!=-1)
				calc.set(Calendar.MINUTE, curCalc.get(Calendar.MINUTE));
		}
		
		return new Date(calc.getTimeInMillis());
	}
}
